<?php
class ClientesController extends AppController {

    var $name = 'Clientes';
    var $appModule = 'Portal';
    var $helpers = array('Html', 'Form', 'Javascript', 'Codigo', 'Time','GetList', 'AdcReporter');
    var $components = array('RequestHandler');    

    function index() {
            $q = $this->getBusqueda($this->data['Cliente']['busqueda']);
            $conditions['Cliente.activo'] = true;
            $conditions['Tercero.empresa_id'] = $this->empresaId();
            $conditions['Tercero.centro_dist_id'] = $this->centroDistId();

            if (!empty($q)){
                $conditions['OR'] = array(
                    'Cliente.codigo SIMILAR TO'=>$q,
                    'Tercero.ruc  SIMILAR TO'=>$this->likeAtCenter($q),
                    'Tercero.numero_documento  SIMILAR TO'=>$this->likeAtCenter($q),
                    'Tercero.razon_social  SIMILAR TO'=>$this->likeAtCenter($q),
                );
            }
            $this->paginate['Cliente'] = array(
				'conditions'=>$conditions,
                'order'=>array('Cliente.codigo'),
                'contain'=>array(
					'Tercero'=>array(
						'fields'=>array(
							'id','centro_dist_id','empresa_id',
							'razon_social','direccion')
					)					
				),
            );
			$clientes = $this->paginate('Cliente');
            $this->set(compact('clientes'));            
    }

    function view($id = null) {
    }

    function add() {
    	
    }

    function edit($id = null) {
        if (!$id && empty($this->data)) {
                $this->Session->setFlash(__('Cliente invalido', true));
                $this->redirect(array('action'=>'index'));
        }
    }
	
	public function buscar($q = null){
		if(!empty($this->data['Cliente']['q'])){
			$q = $this->data['Cliente']['q'];
		} elseif (!empty($this->params['url']['q'])){
			$q = $this->params['url']['q'];
		} elseif (!empty($this->params['form']['q'])){
			$q = $this->params['form']['q'];
		}
						
		if(empty($q)){
			$result = array('Error'=>'No se establecieron los parámetros adecuadamente');
		} else {
			$conditions = array('Cliente.activo' => true);	
			$params = explode('_ID_', $q);			
			if( count($params) == 2){
				$conditions['Cliente.id'] = $params[1];
			} else {
				$conditions['OR']['Cliente.codigo iLike']='%'.strtoupper($q).'%';
				$conditions['OR']['Tercero.razon_social iLike']='%'.strtoupper($q).'%';
			}			
			
			$fields = array(
				'Cliente.id',				
				'Cliente.codigo',	
				'Cliente.puntaje',
				'Cliente.localidad',
				'Tercero.razon_social');
			
			$this->Cliente->Behaviors->attach('Containable');
			$result = $this->Cliente->find('all', array(
				'conditions' => $conditions,
				'contain'=>array('Tercero.razon_social'),							
				'fields' => $fields,
				'order'=>array('Cliente.codigo ASC')));
					
		}		
		//definiendo valores en caso q sea una petici�n para autocompletado
		if(!empty($this->params['url']['autocomplete']) || !empty($this->params['form']['autocomplete'])){
			$res = array();
			foreach($result as $value){
				$res[] = array('value'=>'_ID_'.$value['Cliente']['id'], 'display'=>'<span style="color:gray;font-size:.9em">'.$value['Cliente']['codigo'].'</span><div style="float:right;font-size:.8em" title="'.$value['Tercero']['razon_social'].'">'. $this->neat_trim($value['Tercero']['razon_social'], 24) .'</div>');
			}
			$result = $res;
		}
		
		if ($this->RequestHandler->isAjax()){			
			if(empty($result)){
				$result = array('error'=>'No se encontraron datos');
			}
			$this->_ajaxify($result);
		} else {
			return $result;
		}
	}
}
?>
